import { Util } from 'ibz-core';
import { defineComponent } from 'vue';
const AppStepperProps = {
  /**
   * 双向绑定值
   * @type {any}
   * @memberof AppStepperProps
   */
  value: {
    type: String,
  },

  /**
   * 表单项名称
   * @type {any}
   * @memberof AppStepperProps
   */
  name: String,

  /**
   * 是否禁用
   * @type {boolean}
   * @memberof AppStepperProps
   */
  disabled: Boolean,

  /**
   * 只读模式
   * @type {boolean}
   * @memberof AppStepperProps
   */
  readonly: Boolean,

  /**
   * 最大值
   * @type {string}
   * @memberof AppStepperProps
   */
  maxValue: Number,

  /**
   * 最小值
   * @type {string}
   * @memberof AppStepperProps
   */
  minValue: Number,

  /**
   * 步进值
   * @type {string}
   * @memberof AppStepperProps
   */
  stepValue: {
    type: Number,
    default: 1,
  },

  /**
   * 浮点精度
   * @type {string}
   * @memberof AppStepperProps
   */
  precision: Number,
};

export const AppStepper = defineComponent({
  name: 'AppStepper',
  props: AppStepperProps,
  methods: {
    /**
     * 输入框change事件
     *
     * @param {any} $event
     */
    onChange($event: any) {
      this.valueChange(Number($event.target.value));
    },
    /**
     * 按钮点击
     *
     * @param {number} value
     */
    ButtonClick(value: number) {
      if (Util.isExistAndNotEmpty(this.value)) {
        this.valueChange(Number(this.value) + value);
      } else {
        this.valueChange(value);
      }
    },

    /**
     * @description 值改变
     * @param {number} value
     */
    valueChange(value: number) {
      if (this.maxValue && value > this.maxValue) {
        this.$emit('editorValueChange', this.precision ? this.maxValue.toFixed(this.precision) : this.maxValue);
      } else if (this.minValue && value < this.minValue) {
        this.$emit('editorValueChange', this.precision ? this.minValue.toFixed(this.precision) : this.minValue);
      } else {
        this.$emit('editorValueChange', this.precision ? value.toFixed(this.precision) : value.toString());
      }
    },
  },
  render() {
    return (
      <div class='app-stepper'>
        <button
          type='button'
          class={{ 'stepper-minus': true, 'stepper--disabled': this.disabled, 'stepper--readonly': this.readonly }}
          onClick={() => this.ButtonClick(-this.stepValue)}
        />
        <input
          class='stepper-input'
          value={this.value}
          disabled={this.disabled}
          readonly={this.readonly}
          onChange={($event: any) => this.onChange($event)}
        />
        <button
          type='button'
          class={{ 'stepper-plus': true, 'stepper--disabled': this.disabled, 'stepper--readonly': this.readonly }}
          onClick={() => this.ButtonClick(this.stepValue)}
        />
      </div>
    );
  },
});
